import type {
  User,
  LoginResponse,
  ProxyConfig,
  AccessStats,
  TrafficData,
  ProxyUsageData,
  AccessLog,
  LogQuery,
  SystemSettings,
  ApiResponse,
  PaginatedResponse
} from '../types'

// 模拟数据
const mockUser: User = {
  id: 1,
  username: 'proxy-admin',
  email: 'proxy-admin@example.com',
  avatar: '',
  role: 'proxy-admin',
  createdAt: '2024-01-01T00:00:00Z',
  lastLoginAt: new Date().toISOString()
}

const mockProxies: ProxyConfig[] = [
  {
    id: 1,
    name: '高速代理1',
    host: '192.168.1.100',
    port: 8080,
    protocol: 'http',
    isAnonymous: true,
    isActive: true,
    auth: {
      username: 'proxy_user',
      password: 'proxy_pass'
    },
    loadBalance: 'round_robin',
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: '2024-01-15T00:00:00Z',
    description: '高速HTTP代理服务器'
  },
  {
    id: 2,
    name: '匿名代理2',
    host: '192.168.1.101',
    port: 1080,
    protocol: 'socks5',
    isAnonymous: true,
    isActive: false,
    loadBalance: 'least_connections',
    createdAt: '2024-01-02T00:00:00Z',
    updatedAt: '2024-01-16T00:00:00Z',
    description: 'SOCKS5匿名代理'
  },
  {
    id: 3,
    name: 'HTTPS代理',
    host: '192.168.1.102',
    port: 443,
    protocol: 'https',
    isAnonymous: false,
    isActive: true,
    auth: {
      username: 'https_user',
      password: 'https_pass'
    },
    loadBalance: 'ip_hash',
    createdAt: '2024-01-03T00:00:00Z',
    updatedAt: '2024-01-17T00:00:00Z',
    description: '安全HTTPS代理服务'
  }
]

const mockAccessLogs: AccessLog[] = Array.from({ length: 50 }, (_, index) => ({
  id: index + 1,
  proxyId: Math.floor(Math.random() * 3) + 1,
  proxyName: mockProxies[Math.floor(Math.random() * 3)].name,
  clientIp: `192.168.1.${Math.floor(Math.random() * 255)}`,
  targetUrl: `https://example${Math.floor(Math.random() * 5)}.com/api/data`,
  method: ['GET', 'POST', 'PUT', 'DELETE'][Math.floor(Math.random() * 4)],
  statusCode: [200, 201, 400, 401, 404, 500][Math.floor(Math.random() * 6)],
  requestTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
  responseTime: Math.floor(Math.random() * 1000) + 50,
  userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
  traffic: Math.floor(Math.random() * 10000) + 1000
}))

// 模拟延迟
const delay = (ms: number = 500) => new Promise(resolve => setTimeout(resolve, ms))

// Mock API 类
export class MockApi {
  // 登录
  static async login(username: string, password: string): Promise<ApiResponse<LoginResponse>> {
    await delay()
    
    if (username === 'admin' && password === 'admin123') {
      return {
        code: 200,
        message: '登录成功',
        data: {
          token: 'mock_token_' + Date.now(),
          user: mockUser,
          expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
        }
      }
    } else {
      return {
        code: 401,
        message: '用户名或密码错误',
        data: null
      }
    }
  }

  // 获取用户信息
  static async getUserInfo(): Promise<ApiResponse<User>> {
    await delay()
    return {
      code: 200,
      message: '获取成功',
      data: mockUser
    }
  }

  // 修改密码
  static async changePassword(oldPassword: string, newPassword: string): Promise<ApiResponse<void>> {
    await delay()
    
    if (oldPassword === 'admin123') {
      return {
        code: 200,
        message: '密码修改成功',
        data: null
      }
    } else {
      return {
        code: 400,
        message: '原密码错误',
        data: null
      }
    }
  }

  // 获取代理列表
  static async getProxies(): Promise<ApiResponse<ProxyConfig[]>> {
    await delay()
    return {
      code: 200,
      message: '获取成功',
      data: mockProxies
    }
  }

  // 创建代理
  static async createProxy(proxy: Omit<ProxyConfig, 'id' | 'createdAt' | 'updatedAt'>): Promise<ApiResponse<ProxyConfig>> {
    await delay()
    
    const newProxy: ProxyConfig = {
      ...proxy,
      id: mockProxies.length + 1,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockProxies.push(newProxy)
    
    return {
      code: 200,
      message: '创建成功',
      data: newProxy
    }
  }

  // 更新代理
  static async updateProxy(id: number, proxy: Partial<ProxyConfig>): Promise<ApiResponse<ProxyConfig>> {
    await delay()
    
    const index = mockProxies.findIndex(p => p.id === id)
    if (index === -1) {
      return {
        code: 404,
        message: '代理不存在',
        data: null
      }
    }
    
    mockProxies[index] = {
      ...mockProxies[index],
      ...proxy,
      updatedAt: new Date().toISOString()
    }
    
    return {
      code: 200,
      message: '更新成功',
      data: mockProxies[index]
    }
  }

  // 删除代理
  static async deleteProxy(id: number): Promise<ApiResponse<void>> {
    await delay()
    
    const index = mockProxies.findIndex(p => p.id === id)
    if (index === -1) {
      return {
        code: 404,
        message: '代理不存在',
        data: null
      }
    }
    
    mockProxies.splice(index, 1)
    
    return {
      code: 200,
      message: '删除成功',
      data: null
    }
  }

  // 获取访问统计
  static async getAccessStats(): Promise<ApiResponse<AccessStats>> {
    await delay()
    
    const stats: AccessStats = {
      totalRequests: 125680,
      totalTraffic: 1024 * 1024 * 1024 * 2.5, // 2.5GB
      successRate: 98.5,
      avgResponseTime: 245,
      onlineProxies: mockProxies.filter(p => p.isActive).length,
      totalProxies: mockProxies.length
    }
    
    return {
      code: 200,
      message: '获取成功',
      data: stats
    }
  }

  // 获取流量数据
  static async getTrafficData(days: number = 7): Promise<ApiResponse<TrafficData[]>> {
    await delay()
    
    const data: TrafficData[] = Array.from({ length: days }, (_, index) => {
      const date = new Date()
      date.setDate(date.getDate() - (days - 1 - index))
      
      return {
        date: date.toISOString().split('T')[0],
        requests: Math.floor(Math.random() * 5000) + 2000,
        traffic: Math.floor(Math.random() * 1024 * 1024 * 100) + 1024 * 1024 * 50, // 50-150MB
        successRequests: Math.floor(Math.random() * 4900) + 1950
      }
    })
    
    return {
      code: 200,
      message: '获取成功',
      data
    }
  }

  // 获取代理使用情况
  static async getProxyUsage(): Promise<ApiResponse<ProxyUsageData[]>> {
    await delay()
    
    const data: ProxyUsageData[] = mockProxies.map(proxy => ({
      proxyId: proxy.id,
      proxyName: proxy.name,
      requests: Math.floor(Math.random() * 10000) + 1000,
      traffic: Math.floor(Math.random() * 1024 * 1024 * 50) + 1024 * 1024 * 10,
      successRate: Math.random() * 10 + 90 // 90-100%
    }))
    
    return {
      code: 200,
      message: '获取成功',
      data
    }
  }

  // 获取访问日志
  static async getAccessLogs(query: LogQuery): Promise<ApiResponse<PaginatedResponse<AccessLog>>> {
    await delay()
    
    let filteredLogs = [...mockAccessLogs]
    
    // 应用过滤条件
    if (query.proxyId) {
      filteredLogs = filteredLogs.filter(log => log.proxyId === query.proxyId)
    }
    
    if (query.clientIp) {
      filteredLogs = filteredLogs.filter(log => log.clientIp.includes(query.clientIp!))
    }
    
    if (query.method) {
      filteredLogs = filteredLogs.filter(log => log.method === query.method)
    }
    
    if (query.statusCode) {
      filteredLogs = filteredLogs.filter(log => log.statusCode === query.statusCode)
    }
    
    // 分页
    const total = filteredLogs.length
    const startIndex = (query.page - 1) * query.pageSize
    const endIndex = startIndex + query.pageSize
    const list = filteredLogs.slice(startIndex, endIndex)
    
    return {
      code: 200,
      message: '获取成功',
      data: {
        list,
        total,
        page: query.page,
        pageSize: query.pageSize
      }
    }
  }

  // 获取系统设置
  static async getSystemSettings(): Promise<ApiResponse<SystemSettings>> {
    await delay()
    
    const settings: SystemSettings = {
      siteName: '代理服务管理平台',
      maxConnections: 1000,
      defaultTimeout: 30000,
      logRetentionDays: 30,
      enableAccessLog: true,
      enableRateLimit: true,
      rateLimit: {
        requests: 100,
        window: 60
      }
    }
    
    return {
      code: 200,
      message: '获取成功',
      data: settings
    }
  }

  // 更新系统设置
  static async updateSystemSettings(settings: Partial<SystemSettings>): Promise<ApiResponse<SystemSettings>> {
    await delay()
    
    // 这里应该保存到存储中，现在只是模拟
    const updatedSettings: SystemSettings = {
      siteName: '代理服务管理平台',
      maxConnections: 1000,
      defaultTimeout: 30000,
      logRetentionDays: 30,
      enableAccessLog: true,
      enableRateLimit: true,
      rateLimit: {
        requests: 100,
        window: 60
      },
      ...settings
    }
    
    return {
      code: 200,
      message: '设置更新成功',
      data: updatedSettings
    }
  }
}